package com.jyy.prefabricated.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.dto.ExamApplyDto;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.entity.ExamApply;
import com.jyy.prefabricated.entity.Student;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.entity.TrainingOrganization;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.service.ExamApplyService;
import com.jyy.prefabricated.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;


/**
 * 考试申请
 *
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class ExamApplyController {

    @Autowired
    private ExamApplyService examApplyService;

    @Autowired
    private UserUtils userUtils;

    /**
     * 新增考试申请
     *
     * @param dto
     * @return
     */
    @PostMapping("/exam-apply")
    public AjaxResult insert(@Valid @RequestBody ExamApplyDto dto) {
        SysUser user = userUtils.getCurrentUser();
        if(user.getUserType().equals(UserTypeEnum.TRAININGORGANIZATION.getValue())){
            TrainingOrganization trainingOrganization = userUtils.getCurrentTrainingOrganization();
            dto.setTrainingOrganizationId(trainingOrganization.getId());
            dto.setTrainingOrganizationName(trainingOrganization.getName());
        }

        log.info("Rest request to insert examApply:{}", dto);
        Integer id = examApplyService.insert(dto);
        ExamApply result = examApplyService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 修改考试申请
     *
     * @param dto
     * @return
     */
    @PutMapping("/exam-apply")
    public AjaxResult update(@Valid @RequestBody ExamApplyDto dto) {
        log.info("Rest request to update examApply:{}", dto);
        examApplyService.update(dto);
        ExamApply result = examApplyService.selectById(dto.getId());
        return AjaxResult.success(result);
    }

    /**
     * 批量修改考试申请状态
     *
     * @param dto
     * @return
     */
    @PutMapping("/exams-apply-batch")
    public AjaxResult update(@Valid @RequestBody BatchDto dto) {
        log.info("Rest request to batch-update news:{}", dto);
        examApplyService.batchUpdateStatus(dto);
        return AjaxResult.success();
    }

    /**
     * 查询考试申请详情
     *
     * @param id
     * @return
     */
    @GetMapping("/exam-apply/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find examApply by id:{}", id);
        ExamApply result = examApplyService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 删除考试申请
     *
     * @param id
     * @return
     */
    @DeleteMapping("/exam-apply/{id}")
    public AjaxResult deleteById(@PathVariable Integer id) {
        log.info("Rest request to delete examApply by id:{}", id);
        int row = examApplyService.delete(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 分页查询考试申请列表
     *
     * @param projectId                项目id
     * @param examName                 考试名称
     * @param trainingOrganizationName 机构名称
     * @param pointId                  考核点id
     * @param studentName              学员姓名
     * @param idCard                   学员身份证
     * @param applyStatus              申请状态
     * @param examStatus               考试状态
     * @param applyStartDate           申请开始时间
     * @param applyEndDate             申请结束时间
     * @param pageable                 分页信息
     * @return
     */
    @GetMapping("/exam-apply")
    public AjaxResult selectByParams(@RequestParam(required = false) Integer projectId, @RequestParam(required = false, defaultValue = "") String examName, @RequestParam(required = false, defaultValue = "") String trainingOrganizationName, @RequestParam(required = false) Integer pointId, @RequestParam(required = false, defaultValue = "") String studentName, @RequestParam(required = false, defaultValue = "") String idCard, @RequestParam(required = false) Integer applyStatus, @RequestParam(required = false) Integer examStatus, @RequestParam(required = false, defaultValue = "") String applyStartDate, @RequestParam(required = false, defaultValue = "") String applyEndDate, Pageable pageable) {
        SysUser user = userUtils.getCurrentUser();
        Integer trainingOrganizationId = null;
        if (UserTypeEnum.ADMIN.getValue().equals(user.getUserType())) {
        } else if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            //培训机构职能看自己机构的
            TrainingOrganization trainingOrganization = userUtils.getCurrentTrainingOrganization();
            trainingOrganizationId = trainingOrganization.getId();
        }
        log.info("Rest request to find examApply by projectId:{},examName:{},pointId:{},trainingOrganizationName:{},trainingOrganizationId:{},studentName:{},idCard:{},status:{},applyStartDate{},applyEndDate:{}", projectId, examName, pointId, trainingOrganizationName, studentName, idCard, applyStatus, applyStartDate, applyEndDate);
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<ExamApply> applies = examApplyService.selectByParams(projectId, examName, pointId, trainingOrganizationName, trainingOrganizationId, studentName, idCard, applyStatus, examStatus, applyStartDate, applyEndDate);
        PageInfo<ExamApply> result = new PageInfo<>(applies);
        return AjaxResult.success(result);
    }

    /**
     * 分页查询可以申请考试的学员列表
     *
     * @param examId                 考试id
     * @param projectId              项目id
     * @param name                   学员名称
     * @param idCard                 学员身份证号
     * @param trainingOrganizationId 培训机构
     * @param allocationStatus       分配状态（0未分配，1已分配）
     * @param pageable               分页信息
     * @return
     */
    @GetMapping("/exam-apply-student")
    public AjaxResult selectStudentList(@RequestParam(required = false) Integer examId, @RequestParam(required = false) Integer projectId, @RequestParam(required = false) Integer allocationStatus, @RequestParam(required = false) Integer trainingOrganizationId, @RequestParam(required = false, defaultValue = "") String name, @RequestParam(required = false, defaultValue = "") String idCard, Pageable pageable) {
        log.info("Rest request to find can apply students by examId:{},projectId:{},name:{},idCard:{}", examId, projectId, name, idCard);
        SysUser user = userUtils.getCurrentUser();
        List<Student> students = new ArrayList<>();
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        if (user.getUserType().equals(UserTypeEnum.TRAININGORGANIZATION.getValue())) {
            students = examApplyService.selectCanApplyStudentByTOIdAndExamId(user.getTrainingOrganization().getId(), examId, projectId, name, idCard, allocationStatus);

        } else {
            students = examApplyService.selectCanApplyStudentByTOIdAndExamId(trainingOrganizationId, examId, projectId, name, idCard, allocationStatus);
        }

        PageInfo<Student> result = new PageInfo<>(students);
        return AjaxResult.success(result);
    }

}
